﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;

namespace Manyor.Net
{
    public class SocketClient
    {
        #region -- Event --

        public event EventHandler OnConnectError;

        #endregion

        #region -- Private --

        private IPEndPoint ipep;
        private Socket clientSocket;
        private Byte[] buffer = new Byte[NetConfig.BUFFER_SIZE];

        private Action<byte[], int> _receiveBytesDelegate;
        #endregion
        
        /// <summary>
        /// 构造函数
        /// </summary>
        public SocketClient(Action<byte[], int> action)
        {
            _receiveBytesDelegate = action;
            ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), NetConfig.PORT_SERVER);
            clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            clientSocket.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"), NetConfig.PORT_LOCAL));
            
        }

        /// <summary>
        /// 连接服务器
        /// </summary>
        /// <returns></returns>
        public bool ConnectServer()
        {
            try
            {
                clientSocket.Connect(ipep);
                clientSocket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveMessage), clientSocket);
                return true;
            }
            catch (Exception e)
            {
                if (OnConnectError != null)
                {
                    OnConnectError(null, null);
                }
                return false;
            }
        }
        /// <summary>
        /// 接收消息
        /// </summary>
        /// <param name="ar"></param>
        public void ReceiveMessage(IAsyncResult ar)
        {
            try
            {
                Socket socket = ar.AsyncState as Socket;
                int length = socket.EndReceive(ar);
                if (_receiveBytesDelegate != null)
                {
                    _receiveBytesDelegate(buffer, length);
                }
                socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveMessage), socket);
            }
            catch(Exception e)
            {
                if (OnConnectError != null)
                {
                    OnConnectError(null, null);
                }
            }
        }

        /// <summary>
        /// 发送字节流
        /// </summary>
        /// <param name="bytes"></param>
        public bool SendMessage(byte[] bytes)
        {
            if (clientSocket.Connected)
            {
                try
                {
                    //byte[] bytes = new byte[1024];
                    //bytes = Encoding.ASCII.GetBytes(DateTime.Now.Millisecond.ToString());
                    clientSocket.BeginSend(bytes,0,bytes.Length,SocketFlags.None,null,null);
                    return true;
                }
                catch
                {
                    if (OnConnectError != null)
                    {
                        OnConnectError(null, null);
                    }
                    return false;
                }
            }
            else
                return false;
        }
    }
}
